package com.cus.tom.transfer.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.cus.tom.transfer.App;
import com.cus.tom.transfer.R;
import com.cus.tom.transfer.ac.RightActivity;
import com.cus.tom.transfer.databinding.RightItemBinding;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

public class RightAdapter extends RecyclerView.Adapter {

    final String[] title;
    final String[] desc;
    final String[] right;
    RightActivity activity;

    public RightAdapter(RightActivity activity) {
        title = App.getApp().getResources().getStringArray(R.array.rights);
        desc = App.getApp().getResources().getStringArray(R.array.rights_desc);
        right = new String[]{Permission.MANAGE_EXTERNAL_STORAGE, Permission.READ_CONTACTS, Permission.READ_SMS, Permission.READ_CALL_LOG, Permission.CAMERA, Permission.ACCESS_COARSE_LOCATION};
        this.activity = activity;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RightItemBinding binding = RightItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return title.length;
    }

    class Holder extends RecyclerView.ViewHolder {
        RightItemBinding binding;

        public Holder(RightItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            binding.title.setText(title[p]);
            binding.desc.setText(desc[p]);

            boolean bo = XXPermissions.isGranted(App.getApp(), right[p]);
            if (bo) {
                binding.ok.setVisibility(View.VISIBLE);
                binding.btn.setVisibility(View.INVISIBLE);
            } else {
                binding.ok.setVisibility(View.INVISIBLE);
                binding.btn.setVisibility(View.VISIBLE);
            }
            itemView.setOnClickListener(v -> {
                activity.askPermission(right[p], p, bo);
            });
        }
    }
}
